<template>
    <el-tree-select  v-model="formData"  clearable @change="dataChange"
      :data="treeOptions"   :props="{ value: 'id', label: 'label', children: 'children' }" 
    value-key="id" placeholder="请选择" check-strictly />
    
</template>

<script setup>
import useDictStore from '@/store/modules/dict';
import { dsData } from "@/api/dev/dataset";

const { proxy } = getCurrentInstance();
const emit = defineEmits(['update'])

const formData = ref(null);
const treeOptions = ref([]);

// 记录未匹配的项
const unmatchArray = ref([]);
const props = defineProps({
  modelValue: [String, Number],
  // 数据集
  dsCode: {
    type: String,
    required: true,
  }
});

watch(() => props.modelValue, val => {
  formData.value = val;
},{ deep: true, immediate: true });

watch(() => props.dsCode, val => {
  if(val != null){
    loadDs(val)
  }else{
    treeOptions.value = [];
  }
},{ deep: true, immediate: true });
    
function loadDs(dsCode) {
    let dsKey = "ds_"+dsCode;
    const dicts = useDictStore().getDict(dsKey);
    if (dicts) {
        treeOptions.value = proxy.handleTree(dicts, "id", "pid");
    } else {
        dsData(dsCode).then(resp => {
            treeOptions.value = proxy.handleTree(resp.data, "id", "pid");
            useDictStore().setDict(dsKey, resp.data);
        });
    }
}

function dataChange() {    
    emit("update:modelValue", formData.value);
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
